from datetime import datetime

from models import db


class User(db.Model):
    """用户表"""
    __tablename__ = "user"
    # 用户id
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), nullable=False)
    icon = db.Column(db.String(200), default='/static/index/images/person_1.jpg')
    telephone = db.Column(db.String(30), nullable=False)
    password = db.Column(db.String(30), nullable=False)


class Product(db.Model):
    """商品"""
    __tablename__ = "product"
    # 商品编号
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    # 商品名字
    name = db.Column(db.String(200), unique=True, nullable=False)
    # 商品价格
    price = db.Column(db.Float, nullable=False)
    # 库存
    amount = db.Column(db.Integer, nullable=False)
    # 描述
    description = db.Column(db.String(300))
    # 销量
    sales = db.Column(db.Integer, default=0)
    # 商品评分
    rating = db.Column(db.Integer, default=0)
    # 商品类别
    category_id = db.Column(db.Integer, db.ForeignKey("category.id"))
    # 商品图片
    img_url = db.Column(db.String(200), default=None)
    category = db.relationship("Category", backref='product')
    cart_users = db.relationship("User", secondary='cart', lazy="dynamic", backref="my_cart")


class Category(db.Model):
    """商品类别表"""
    __tablename__ = "category"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(30), nullable=False)


class Review(db.Model):
    """商品评论表"""
    __tablename__ = "review"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
    product_id = db.Column(db.Integer, db.ForeignKey("product.id"))
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now())
    user = db.relationship("User", backref="reviews")


class Cart(db.Model):
    """购物车"""
    __tablename__ = "cart"
    user_id = db.Column("user_id", db.Integer, db.ForeignKey("user.id"), primary_key=True)
    product_id = db.Column("product_id", db.Integer, db.ForeignKey("product.id"), primary_key=True)
    quantity = db.Column("quantity", db.Integer)


class Order(db.Model):
    __tablename__ = "order"
    id = db.Column("id", db.Integer, primary_key=True, autoincrement=True)
    create_time = db.Column(db.DateTime, default=datetime.now())
    user_id = db.Column("user_id", db.Integer, db.ForeignKey("user.id"))
    products = db.Column("products", db.String(500))
    total_price = db.Column("total_price", db.Integer)
